package com.alu4r.atcrowdfunding.manager.controller;

import com.alu4r.atcrowdfunding.util.AjaxResult;
import com.alu4r.atcrowdfunding.util.JsonMessageResult;
import com.alu4r.atcrowdfunding.util.Page;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sun.nio.ch.IOUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/process")
public class ProcessController {
    @Autowired
    private RepositoryService repositoryService ;


    @ResponseBody
    @RequestMapping("/showImgProDef")
    public void showImgProDef(String id, HttpServletResponse response) throws IOException {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(id).singleResult();
        InputStream resourceAsStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), processDefinition.getDiagramResourceName());
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.copy(resourceAsStream,outputStream);
    }

    @RequestMapping("/showImg")
    public String showImg(String id){
        System.out.println("查看流程图");
        return "process/showImg";
    }
    @ResponseBody
    @RequestMapping("/doDelete")
    public Object doDelete(String id){
        JsonMessageResult jsonMessageResult = null;
        try {
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(id).singleResult();

            repositoryService.deleteDeployment(processDefinition.getDeploymentId(),true);
            jsonMessageResult = JsonMessageResult.success();
        }catch (Exception e){
            e.printStackTrace();
            jsonMessageResult = JsonMessageResult.fail();
        }

        return jsonMessageResult;
    }

    @ResponseBody
    @RequestMapping("/deploy")
    public Object deploy(HttpServletRequest request){
        JsonMessageResult jsonMessageResult = null;
        System.out.println("上传流程图");
        try {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            MultipartFile multipartFile = multipartHttpServletRequest.getFile("processDefFile");
            repositoryService.createDeployment()
                    .addInputStream(multipartFile.getOriginalFilename(),multipartFile.getInputStream())
                    .deploy();
            jsonMessageResult = JsonMessageResult.success();
        }catch (Exception e){
            e.printStackTrace();
            jsonMessageResult = JsonMessageResult.fail();
        }

        return jsonMessageResult;
    }

    @ResponseBody
    @RequestMapping("/doIndex")
    public Object doIndex(@RequestParam(value="pageno",required=false,defaultValue="1") Integer pageno,
                          @RequestParam(value="pagesize",required=false,defaultValue="10") Integer pagesize){

        AjaxResult result = new AjaxResult();

        try {
            Page page = new Page(pageno,pagesize);

            ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
            //查询流程定义集合数据,可能出现了自关联,导致Jackson组件无法将集合序列化为JSON串.
            List<ProcessDefinition> listPage = processDefinitionQuery.listPage(page.getStartIndex(), pagesize);


            List<Map<String,Object>> mylistPage = new ArrayList<Map<String,Object>>();

            for (ProcessDefinition processDefinition : listPage) {

                Map<String,Object> pd = new HashMap<String,Object>();
                pd.put("id", processDefinition.getId());
                pd.put("name", processDefinition.getName());
                pd.put("key", processDefinition.getKey());
                pd.put("version", processDefinition.getVersion());

                mylistPage.add(pd);
            }


            Long totalsize = processDefinitionQuery.count();

            page.setData(mylistPage);

            page.setTotalsize(totalsize.intValue());

            result.setPage(page);
            result.setSuccess(true);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMassage("查询流程定义失败!");
            e.printStackTrace();
        }


        return result;
    }
}
